<template>
  <div class="app-container">

    <!-- 查询条件 -->
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" :label-width="labelWidth">

      <el-form-item label="管理对象" prop="manageObject" v-if="showSearchField('manageObject')">
        <el-select v-model="manageObject" placeholder="请选择管理对象" filterable size="small" @change="searchFieldChanged('manageObject', $event)">
          <el-option v-for="item in manageObjectOptions" :key="item.key" :label="item.label" :value="item.value" :disabled="item.disabled"></el-option>
        </el-select>
        <i class="el-icon-remove-outline" @click="toggleSearchShow('manageObject')"></i>
      </el-form-item>
      <el-form-item label="应用" prop="applicationId" v-if="showSearchField('applicationId')">
        <el-select v-model="queryParams.applicationId" placeholder="请选择应用" clearable filterable size="small" @change="searchFieldChanged('applicationId', $event)">
          <el-option v-for="item in pageModelConfig.searchColumnsOptions['applicationId']" :key="item.key" :label="item.label" :value="item.value" :disabled="item.disabled"></el-option>
        </el-select>
        <i class="el-icon-remove-outline" @click="toggleSearchShow('applicationId')"></i>
      </el-form-item>
      <el-form-item label="模块" prop="moduleId" v-if="showSearchField('moduleId')">
        <el-select v-model="queryParams.moduleId" placeholder="请选择模块" clearable filterable size="small" @change="searchFieldChanged('moduleId', $event)">
          <el-option v-for="(item, index) in pageModelConfig.searchColumnsOptions['moduleId']" :key="item.key" :label="item.label" :value="item.value" :disabled="item.disabled"></el-option>
        </el-select>
        <i class="el-icon-remove-outline" @click="toggleSearchShow(1)"></i>
      </el-form-item>
      <el-form-item label="数据源" prop="datasource" v-if="showSearchField('datasource')">
        <el-select v-model="queryParams.datasource" placeholder="请选择数据源" clearable filterable size="small" @change="searchFieldChanged('datasource', $event)">
          <el-option v-for="(item, index) in pageModelConfig.searchColumnsOptions['datasource']" :key="item.key" :label="item.label" :value="item.value" :disabled="item.disabled"></el-option>
        </el-select>
        <i class="el-icon-remove-outline" @click="toggleSearchShow(2)"></i>
      </el-form-item>
      <el-form-item label="数据库" prop="tableSchema" v-if="showSearchField('tableSchema')">
        <el-select v-model="queryParams.tableSchema" placeholder="请选择数据库" clearable filterable size="small" @change="searchFieldChanged('tableSchema', $event)">
          <el-option v-for="(item, index) in pageModelConfig.searchColumnsOptions['tableSchema']" :key="item.key" :label="item.label" :value="item.value":disabled="item.disabled"></el-option>
        </el-select>
        <i class="el-icon-remove-outline" @click="toggleSearchShow(3)"></i>
      </el-form-item>
      <el-form-item label="表名称" prop="tableName" v-if="showSearchField('tableName')">
        <el-select v-model="queryParams.tableName" placeholder="请输入表名称" clearable filterable size="small" @change="searchFieldChanged('tableName', $event)" @keyup.enter.native="handleQuery">
          <el-option v-for="(item, index) in pageModelConfig.searchColumnsOptions['tableName']" :key="item.key" :label="item.label" :value="item.value":disabled="item.disabled"></el-option>
        </el-select>
        <i class="el-icon-remove-outline" @click="toggleSearchShow(4)"></i>
      </el-form-item>
      <el-form-item label="表描述" prop="tableComment" v-if="showSearchField('tableComment')">
        <el-select v-model="queryParams.tableComment" placeholder="请输入表描述" clearable filterable size="small" @change="searchFieldChanged('tableComment', $event)" @keyup.enter.native="handleQuery">
          <el-option v-for="(item, index) in pageModelConfig.searchColumnsOptions['tableComment']" :key="item.key" :label="item.label" :value="item.value":disabled="item.disabled"></el-option>
        </el-select>
        <i class="el-icon-remove-outline" @click="toggleSearchShow(5)"></i>
      </el-form-item>
      <el-form-item label="时间范围" prop="dateRange" v-if="showSearchField('dateRange')">
        <el-date-picker v-model="queryParams.params.dateRange" style="width: 225px;" value-format="yyyy-MM-dd" type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
        <i class="el-icon-remove-outline" @click="toggleSearchShow('dateRange')"></i>
      </el-form-item>
      <el-form-item label="全文搜索" prop="searchValue" v-if="showSearchField('searchValue')">
        <el-select v-model="queryParams.searchValue" placeholder="请输入要检索的内容" clearable filterable remote size="small" @change="searchFieldChanged('searchValue', $event)">
          <el-option v-for="item in searchValueOptions" :key="item.key" :label="item.label" :value="item.value" :disabled="item.disabled"></el-option>
        </el-select>
        <i class="el-icon-remove-outline" @click="toggleSearchShow('searchValue')"></i>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="getList">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="searchFields"></right-toolbar>
      </el-form-item>
    </el-form>

    <!-- 应用、模块信息 -->
    <el-row :gutter="20">
      <el-col :xs="24" :sm="12" :md="8" :lg="6">
        <el-card class="box-card" v-if="application != null && false">
          <div slot="header" class="clearfix">
            <span>应用程序</span>
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="searchFields"></right-toolbar>
          </div>
          <div v-if="application!=null">
            <ul class="list-group list-group-striped">
              <li class="list-group-item">
                <svg-icon icon-class="user" />应用名称
                <div class="pull-right">{{ application.name }}</div>
              </li>
              <li class="list-group-item">
                <svg-icon icon-class="phone" />应用描述
                <div class="pull-right">{{ application.description }}</div>
              </li>
              <li class="list-group-item">
                <svg-icon icon-class="email" />表前缀
                <div class="pull-right">{{ application.tablePrefix }}</div>
              </li>
              <li class="list-group-item">
                <svg-icon icon-class="tree" />包路径
                <div class="pull-right" v-if="application.orgList && application.orgList.length>0">{{ application.orgList[0].deptName }} / {{ postGroup }}</div>
              </li>
              <li class="list-group-item">
                <svg-icon icon-class="tree" />作者
                <div class="pull-right" v-if="application.orgList && application.orgList.length>0">{{ application.orgList[0].children[0].deptName }} / {{ postGroup }}</div>
              </li>
            </ul>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :md="8" :lg="6">
        <el-card class="box-card" v-if="module != null && false">
          <div slot="header" class="clearfix">
            <span>功能模块</span>
          </div>
          <div>
            <ul class="list-group list-group-striped">
              <li class="list-group-item">
                <svg-icon icon-class="user" />模块名称
                <div class="pull-right">{{ module.moduleName }}</div>
              </li>
              <li class="list-group-item">
                <svg-icon icon-class="phone" />应用描述
                <div class="pull-right">{{ module.moduleDescription }}</div>
              </li>
              <li class="list-group-item">
                <svg-icon icon-class="email" />模块前缀
                <div class="pull-right">{{ module.modulePrefix }}</div>
              </li>
              <li class="list-group-item">
                <svg-icon icon-class="tree" />包路径
                <div class="pull-right">{{ module.packageName }}</div>
              </li>
              <li class="list-group-item">
                <svg-icon icon-class="tree" />作者
                <div class="pull-right">{{ module.author }}</div>
              </li>
            </ul>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 头部工具条 -->
    <el-row :gutter="10" class="mb8" v-if="manageObject=='datasource'">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAddDatasource"
          v-hasPermi="['codegen:table:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="el-icon-upload" size="mini" @click="openImportDatasource"
          v-hasPermi="['codegen:table:import']">导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['codegen:table:delete']">删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
    </el-row>

    <el-row :gutter="10" class="mb8" v-if="manageObject=='table'">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-download" size="mini" @click="handleGen" v-hasPermi="['codegen:table:gencode']">生成</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="el-icon-upload" size="mini" @click="openImportTable" v-hasPermi="['codegen:table:import']">导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="el-icon-upload" size="mini" @click="handleSyncDb" v-hasPermi="['codegen:table:sync']">同步</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleEditTable" v-hasPermi="['codegen:table:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete" v-hasPermi="['codegen:table:delete']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-tool" size="mini" :disabled="multiple" @click="handleOptimize" v-hasPermi="['codegen:table:edit']">优化</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
    </el-row>

    <!-- 业务实体表列表区 -->
    <el-table v-loading="loading" :data="tableList" @selection-change="handleSelectionChange" v-if="manageObject=='table'">
      <el-table-column type="selection" align="center" width="50"></el-table-column>
      <el-table-column label="序号" type="index" width="50" align="center">
        <template v-slot:default="scope">
          <span>{{(queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1}}</span>
        </template>
      </el-table-column>
      <el-table-column label="数据源" align="center" prop="datasource" :show-overflow-tooltip="true" width="100" v-if="showListField('datasource')"/>
      <el-table-column label="数据库" align="center" prop="tableSchema" :show-overflow-tooltip="true" width="130" v-if="showListField('tableSchema')"/>
      <el-table-column label="表名称" align="center" prop="tableName" :show-overflow-tooltip="true" width="150" v-if="showListField('tableName')"/>
      <el-table-column label="表描述" align="center" prop="tableComment" :show-overflow-tooltip="true" width="120" v-if="showListField('tableComment')"/>
      <el-table-column label="实体类" align="center" prop="className" :show-overflow-tooltip="true" width="150" v-if="showListField('className')"/>
      <el-table-column label="模块"  align="center" prop="mouleId" :show-overflow-tooltip="true" width="150" v-if="showListField('moduleId')"/>
      <el-table-column label="创建时间" align="center" prop="createTime" width="160" v-if="showListField('createTime')"/>
      <el-table-column label="更新时间" align="center" prop="updateTime" width="160" v-if="showListField('updateTime')"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template v-slot:default="scope">
          <el-button type="text" size="small" icon="el-icon-view"     @click="handlePreview(scope.row)"   v-hasPermi="['codegen:table:preview']"  >预览</el-button>
          <el-button type="text" size="small" icon="el-icon-edit"     @click="handleEditTable(scope.row)" v-hasPermi="['codegen:table:edit']"     >编辑</el-button>
          <el-button type="text" size="small" icon="el-icon-delete"   @click="handleDelete(scope.row)"    v-hasPermi="['codegen:table:delete']"   >删除</el-button>
          <el-button type="text" size="small" icon="el-icon-refresh"  @click="handleSyncDb(scope.row)"    v-hasPermi="['codegen:table:sync']"     >同步</el-button>
          <el-button type="text" size="small" icon="el-icon-download" @click="handleGen(scope.row)"       v-hasPermi="['codegen:table:gencode']"  >生成代码</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 数据源表列表区 -->
    <el-table v-loading="loading" :data="datasourceList" @selection-change="handleSelectionChange" v-if="manageObject=='datasource'">
      <el-table-column type="selection" align="center" width="50"></el-table-column>
      <el-table-column label="序号" type="index" width="50" align="center">
        <template v-slot:default="scope">
          <span>{{(queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1}}</span>
        </template>
      </el-table-column>
      <el-table-column label="数据源名称" align="center" prop="name" :show-overflow-tooltip="true" width="100" v-if="showListField('name')"/>
      <el-table-column label="显示名称" align="center" prop="displayName" :show-overflow-tooltip="true" width="130" v-if="showListField('displayName')"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template v-slot:default="scope">
          <el-button type="text" size="small" icon="el-icon-edit" @click="handleEditDatasource(scope.row)"
            v-hasPermi="['codegen:table:edit']">编辑</el-button>
          <el-button type="text" size="small" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['codegen:table:delete']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 应用列表区 -->
    <el-table v-loading="loading" :data="applicationList" @selection-change="handleSelectionChange" v-if="manageObject=='application'">
      <el-table-column type="selection" align="center" width="50"></el-table-column>
      <el-table-column label="序号" type="index" width="50" align="center">
        <template v-slot:default="scope">
          <span>{{(queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1}}</span>
        </template>
      </el-table-column>
      <el-table-column label="数据源名称" align="center" prop="name" :show-overflow-tooltip="true" width="100" v-if="showListField('name')"/>
      <el-table-column label="显示名称" align="center" prop="displayName" :show-overflow-tooltip="true" width="130" v-if="showListField('displayName')"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template v-slot:default="scope">
          <el-button type="text" size="small" icon="el-icon-edit" @click="handleEditTable(scope.row)"
            v-hasPermi="['codegen:table:edit']">编辑</el-button>
          <el-button type="text" size="small" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['codegen:table:delete']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页控制 -->
    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" v-if="manageObject=='table'"/>

    <!-- 添加或修改对话框 -->
    <el-dialog :title="datasourceDialogTitle" :visible.sync="datasourceDialog" width="600px" append-to-body>
      <el-form ref="datasourceForm" :model="datasource" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="名称" prop="name">
              <el-input v-model="datasource.name" placeholder="请输入名称" maxlength="30" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="显示名称" prop="displayName">
              <el-input v-model="datasource.displayName" placeholder="请输入显示名称" maxlength="30" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户名称" prop="userName">
              <el-input v-model="datasource.userName" placeholder="请输入用户名称" maxlength="30" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户密码" prop="password">
              <el-input v-model="datasource.password" placeholder="请输入用户密码" type="password" maxlength="20" show-password/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 代码生成对话框 -->
    <el-dialog :title="codeGenConfig.title" :visible.sync="codeGenConfig.open" width="800px" append-to-body>
      <el-form ref="codeGenConfigForm" :model="codeGenConfig.form" label-width="110px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="应用名称" prop="applicationId">
              <el-select v-model="codeGenConfig.form.applicationId" >
                <el-option v-for="item in pageModelConfig.searchColumnsOptions['applicationId']" :key="item.key" :label="item.label" :value="item.value" :disabled="item.disabled"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="应用相关" prop="genApplicationCode">
              <el-checkbox v-model="codeGenConfig.form.genApplicationCode" /> 生成应用相关代码
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="模块相关" prop="genModuleCode">
              <el-checkbox v-model="codeGenConfig.form.genModuleCode" /> 生成模块相关代码
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="业务相关" prop="genBusinessCode">
              <el-checkbox v-model="codeGenConfig.form.genBusinessCode" /> 生成业务相关代码
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="实体相关" prop="genEntityCode">
              <el-checkbox v-model="codeGenConfig.form.genEntityCode" /> 生成实体相关代码
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="实体映射表" prop="genMapperCode">
              <el-checkbox v-model="codeGenConfig.form.genMapperCode" /> 生成实体映射表
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleCodeGenConfig">确 定</el-button>
        <el-button @click="codeGenConfig.open = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 代码生成预览 -->
    <el-dialog :title="preview.title" :visible.sync="preview.open" width="80%" top="5vh" append-to-body class="scrollbar">
      <el-tabs v-model="preview.activeName">
        <el-tab-pane v-for="(value, key) in preview.data"
          :label="key.substring(key.lastIndexOf('/')+1,key.indexOf('.vm'))"
          :name="key.substring(key.lastIndexOf('/')+1,key.indexOf('.vm'))" :key="key">
          <el-link :underline="false" icon="el-icon-document-copy" v-clipboard:copy="value"
            v-clipboard:success="clipboardSuccess" style="float:right">复制</el-link>
          <pre><code class="hljs" v-html="highlightedCode(value, key)"></code></pre>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>

    <!-- 代码优化操作 -->
    <el-dialog title="代码优化操作" :visible.sync="optimizedOperation.open" width="80%" top="5vh" append-to-body class="scrollbar">
      <el-tabs v-model="optimizedOperation.activeName">
        <el-tab-pane v-for="(value, key) in optimizedOperation.data"
                     :label="key.substring(key.lastIndexOf('/')+1,key.indexOf('.vm'))"
                     :name="key.substring(key.lastIndexOf('/')+1,key.indexOf('.vm'))" :key="key">
          <el-link :underline="false" icon="el-icon-document-copy" v-clipboard:copy="value"
                   v-clipboard:success="clipboardSuccess" style="float:right">复制</el-link>
          <pre><code class="hljs" v-html="highlightedCode(value, key)"></code></pre>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>

    <!-- 导入业务实体表 -->
    <import-table ref="importTable" @ok="handleQuery" />

  </div>
</template>

<style>
  .el-input {
    width: 220px;
  }
</style>

<script>
  import { searchChanged, list, delTable, optimizeTable, previewTable, genCode, syncDb ,} from "@/api/tool/gen/table";
  import {  } from "@/api/tool/gen/application";
  import {  } from "@/api/tool/gen/module";
  import { listDbSchema, getDatasource, listDatasource } from "@/api/tool/gen/dbinfo";
  import {  } from "@/api/tool/gen";
  import application from "../application/index.vue";
  import importTable from "./importTable";
  import datasource from "../datasource/index";
  import { useRouter } from 'vue-router';

  // import hljs from "highlight.js/lib/highlight";
  // import "highlight.js/styles/github-gist.css";
  // import { option } from "runjs";
  // hljs.registerLanguage("java", require("highlight.js/lib/languages/java"));
  // hljs.registerLanguage("xml", require("highlight.js/lib/languages/xml"));
  // hljs.registerLanguage("yml", require("highlight.js/lib/languages/yaml"));
  // hljs.registerLanguage("html", require("highlight.js/lib/languages/xml"));
  // hljs.registerLanguage("vue", require("highlight.js/lib/languages/xml"));
  // hljs.registerLanguage("javascript", require("highlight.js/lib/languages/javascript"));
  // hljs.registerLanguage("sql", require("highlight.js/lib/languages/sql"));

  export default {
    name: "Gen",
    components: {
      importTable,
      application,
      datasource
    },
    data() {
      return {
        // 版本号
        version: "1.4.36",
        loading: true,
        manageObject: "table",
        // 唯一标识符
        uniqueId: "",
        // 选中表数组
        tableIds: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 全文检索
        searchValue: [],
        // 可搜索选项
        searchValueOptions: [
        ],
        // 数据源列表
        datasourceList: [],
        // 数据源列表
        applicationList: [],
        // 表数据
        tableList: [],
        // 当前应用
        application: undefined,
        // 当前模块
        module: undefined,
        // 搜索字段信息
        searchFields: [
        ],
        // 列信息
        columns: [
          { key: 'datasource'     , label: `数据源`  , visible: false },
          { key: 'tableSchema'    , label: `数据库`  , visible: true },
          { key: 'tableName'      , label: `表名`    , visible: true },
          { key: 'className'      , label: `实体类`   , visible: true },
          { key: 'tableComment'   , label: `表名描述` , visible: true },
          { key: 'createTime'     , label: `创建时间` , visible: true },
          { key: 'updateTime'     , label: `更新时间` , visible: true },
        ],
        // 管理对象
        manageObjectOptions: [
          {key:"datasource", value:"datasource", label: "数据源"},
          {key:"application", value:"application", label: "应用程序"},
          {key:"module", value:"module", label: "功能模块"},
          {key:"table", value:"table", label: "业务实体表"},
        ],
        // 待选应用列表
        applicationIdOptions: [],
        // 待选模块列表
        moduleIdOptions: [],
        // 待选数据源
        datasourceOptions: [],
        // 待选数据库
        tableSchemaOptions: [],
        // 待选表名
        tableNameOptions: [],
        // 表注解待选项
        tableCommentOptions: [],
        // 页面模型配置
        pageModelConfig:{
          // 模块
          moduleName: "gen",
          moduleLabel: "代码生成",
          businessName: "table",
          businessLabel: "实体表",
          name: "table",
          label: "实体表",
          // 基本字体尺寸
          fontSize: 16,
          labelWidth: "68px",
          // 标签栏字符数(全角)
          labelSize: 6,
          searchColumns: [
          ],
          searchColumnsOptions: {},
          columns:[
          ],
          columnsOptions: {"datasource": [{
              "key": null,
              "value": "pandamimi-cloud",
              "label": "pandamimi-cloud",
              "disabled": null
            }]}
        },
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,

          applicationId: 5,
          moduleId: undefined,
          datasource: undefined,
          tableSchema: undefined,
          tableName: undefined,
          tableComment: undefined,
          searchValue: undefined,
          params: {
            // 日期范围
            dateRange: "",
            changedField: null
          }
        },
        datasource: {},
        datasourceDialogTitle: '',
        datasourceDialog: false,
        // 表单校验
        rules: {
        },
        //
        codeGenConfig: {
          open: false,
          title: "代码生成配置",
          genType: undefined,
          genPath: undefined,
          form: {
            applicationId: undefined,
            tableIds: undefined,

            /**
             * 生成应用相关代码
             */
            genApplicationCode: true,

            /**
             * 生成模块相关代码
             */
            genModuleCode: true,

            /**
             * 生成业务相关代码
             */
            genBusinessCode: true,

            /**
             * 生成实体表相关代码
             */
            genEntityCode: true,

            /**
             * 生成实体映射文件
             */
            genMapperCode: true,

          },
        },
        // 预览参数
        preview: {
          open: false,
          title: "代码预览",
          data: {},
          activeName: "domain.java"
        },
        // 优化操作
        optimizedOperation: {
          open: false,
          data: {},
          activeName: "domain.java"
        }
      };
    },
    setup() {
      const router = useRouter();

      function navigateToPath(value) {
        router.push("/tool/gen/" + value);
      }

      // 你的其他逻辑...

      return {
        navigateToPath,
        // 其他返回值...
      };
    },
    created() {
      // 收集查询参数，默认均以 params 下的通用参数方式提交
      Object.keys(this.$route.query).forEach(key => {
        // 检查 key 是否是我们想要特别处理的参数
        if (key === 'pageNum' || key === 'applicationId') {
          // 对这些参数进行特别处理，比如转换为数字
          this.queryParams[key] = Number(this.$route.query[key]);
        } else if (!(key in this.queryParams)) {
          // 如果 key 不在我们已知的 queryParams 属性中，则将其添加到 params 对象中
          // 注意：这里我们假设 this.queryParams.params 已经是一个对象
          this.queryParams.params[key] = this.$route.query[key];
        }
        // 注意：我们没有对 't' 进行特别处理，因为它会被上面的 else if 语句捕获并添加到 params 中
      });
      // 初始化搜索字段
      this.searchFieldChanged();
    },
    activated() {
      const time = this.$route.query.t;
      if (time != null && time !== this.uniqueId) {
        this.uniqueId = time;
        this.getList();
      }
    },
    mounted() {
      this.$nextTick(() => {
        const formItems = this.$refs.queryForm.fields;
        formItems.forEach(item => {
          // 检查此字段是否已存在于 searchFields 中
          const existingField = this.searchFields.find(field => field.key === item.prop);
          if (!existingField) {
            // 如果不存在，则添加新字段
            this.searchFields.push({
              key: item.prop,
              label: item.label,
              visible: true
            });
          }
        });
      });
    },
    computed: {
      // 计算label-width
      labelWidth(){
        return `${ this.pageModelConfig.fontSize * this.pageModelConfig.labelSize }px`;
      }
    },
    methods: {
      // 是否显示指定搜索字段
      showSearchField(field) {
        let isShow = true;
        if(this.searchFields){
          let item = this.searchFields.find(item => item.key === field);
          if(item){
            isShow = item.visible;
          }
        }
        return isShow;
      },
      // 是否显示指定列表字段
      showListField(field) {
        let isShow = true;
        if(this.columns){
          let item = this.columns.find(item => item.key === field);
          if(item){
            isShow = item.visible;
          }
        }
        return isShow;
      },
      toggleSearchShow(field) {
        let searchField = null;
        if(Number.isInteger(field)){
          searchField = this.searchFields[field].key;
        }else{
          for(let i=0;i<this.searchFields.length;i++){
            if(this.searchFields[i].key===field){
              searchField = this.searchFields[i];
              break;
            }
          }
        }
        if(searchField){
          searchField.visible = !searchField.visible; // 切换显示状态
          console.log("调试：searchField="+searchField.key);
        }
      },
      // 搜索字段改变
      searchFieldChanged(changedField, value) {
        if(changedField === 'manageObject'){
          if(value !== 'table'){
            // 非当前业务，直接跳转目标页面
            router.push({"path":"/tool/gen/"+value});
          }else{
            changedField = null;
            this.queryParams
          }
        }

        this.queryParams.params['width'] = window.innerWidth;
        this.queryParams.params['height'] = window.innerHeight;

        let queryParams = this.addDateRange(this.queryParams, this.dateRange);
        queryParams.params.searchPropertyList = Object.keys(this.queryParams).filter(prop => !['pageSize', 'pageNum', 'params'].includes(prop));
        if(changedField!=null&&changedField!==""){
          queryParams.params.changedField = changedField;
        }
        searchChanged(queryParams).then(res => {
          if(res.pageModelConfig){
            // 遍历res.pageModelConfig的键
            for (const key in res.pageModelConfig) {
              if (res.pageModelConfig.hasOwnProperty(key)) {
                // 检查this.pageModelConfig中是否也存在该键
                if (this.pageModelConfig.hasOwnProperty(key)) {
                  // 如果this.pageModelConfig是一个嵌套对象，并且res.pageModelConfig[key]也是对象，
                  // 你可能需要递归更新或仅更新某些特定的属性
                  if (typeof this.pageModelConfig[key] === 'object' && typeof res.pageModelConfig[key] === 'object') {
                    // 这里假设你只想更新searchColumnsOptions或类似的嵌套对象
                    if (key === 'searchColumnsOptions') {
                      // 假设res.pageModelConfig[key]是一个包含新selectOptions的对象数组
                      this.pageModelConfig[key] = { ...this.pageModelConfig[key], ...res.pageModelConfig[key] };
                      // 注意：如果res.pageModelConfig[key]是数组，并且你想合并数组，你可能需要
                      // 使用Array.prototype.concat或扩展运算符（但扩展运算符在这里不适用，因为它是浅拷贝）
                      // 或者，如果res.pageModelConfig[key]直接包含新的selectOptions，你可能需要遍历它们并更新
                    } else if (Array.isArray(this.pageModelConfig[key]) && Array.isArray(res.pageModelConfig[key])) {
                      // 如果两个都是数组，并且你想合并它们
                      this.pageModelConfig[key] = [...this.pageModelConfig[key], ...res.pageModelConfig[key]];
                      // 注意：这可能会导致重复，如果这不是你想要的，你可能需要先去重
                    } else {
                      // 对于其他简单的对象或值，直接赋值
                      this.pageModelConfig[key] = res.pageModelConfig[key];
                    }
                  } else {
                    // 对于非嵌套对象或值，直接赋值
                    this.pageModelConfig[key] = res.pageModelConfig[key];
                  }
                }
                // 如果this.pageModelConfig中没有该键，但你可能想添加它，可以去掉if条件
                // this.pageModelConfig[key] = res.pageModelConfig[key];

                // 调试信息
                if (key === 'searchColumnsOptions' && Array.isArray(res.pageModelConfig[key])) {
                  // 假设res.pageModelConfig[key]是包含selectOptions的数组
                  res.pageModelConfig[key].forEach(obj => {
                    console.log("调试1：obj.key= " + obj.key + " , obj.selectOptions=" + obj.selectOptions);
                  });
                }
              }
            }
          }

          this.application = res.data.params.application;
          this.module = res.data.module;

          console.log("调试0：", res.searchColumns, "[obj.selectOptions]", res.searchColumns.length);
          if(res.searchColumns){
            this.pageModelConfig.searchColumns = res.searchColumns;
            this.pageModelConfig.searchColumns.forEach(obj => {
              if (obj && obj.key && obj.selectOptions) {
                this.pageModelConfig.searchColumnsOptions[obj.key] = obj.selectOptions;
                console.log("调试1：obj.key= " + obj.key + " , obj.selectOptions=" + obj.selectOptions);
              }
            });
          }

          this.applicationIdOptions = res.data.params.applicationIdOptions;
          this.moduleIdOptions = res.data.params.moduleIdOptions;
          this.datasourceOptions = res.data.params.datasourceOptions;
          this.tableSchemaOptions = res.data.params.tableSchemaOptions;
          this.tableNameOptions = res.data.params.tableNameOptions;
          this.tableCommentOptions = res.data.params.tableCommentOptions;

          // 如果检索条件验证通过，刷新列表
          if(res.data.params.searchValid){
            this.getList();
          } else {
            this.tableList = [];
            this.loading = false;
          }
        });
        if (changedField === 'applicationId' && value) {
          let param = {applicationId: value};
          const query = { ...this.$route.query, ...param };
          this.$router.replace({ path: this.$route.path, query });
        }
      },
      /** 查询表集合 */
      getList() {
        this.loading = true;
        if(this.manageObject==='table'){
          let queryParams = this.addDateRange(this.queryParams, this.dateRange);
          list(queryParams).then(response => {
            this.tableList = response.rows;
            this.total = response.total;
            this.loading = false;
          });
        }else if(this.manageObject==='application'){
        }else if(this.manageObject==='datasource'){
        }
      },
      submitForm(){

      },
      cancel(){

      },
      // 表单重置
      resetDatasource() {
        this.datasource = {
          name: undefined,
          displayName: undefined,
          userName: undefined,
          password: undefined,
        };
        this.resetForm("datasourceForm");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 新增数据源按钮操作 */
      handleAddDatasource() {
        this.resetDatasource();
        getDatasource().then(response => {
          // this.postOptions = response.posts;
          // this.roleOptions = response.roles;
          this.datasourceDialog = true;
          this.title = "添加数据源";
          this.datasource.password = "";
        });
      },
      /** 修改按钮操作 */
      handleEditDatasource(row) {
        getDatasource(row.id).then(response => {
          this.datasource = response.data;
          // this.roleOptions = response.roles;
          // this.$set(this.form, "deptIds", response.data.deptIds);
          this.datasourceDialog = true;
          this.datasourceDialogTitle = "修改数据源";
        });
      },
      /** 生成代码操作 */
      handleGen(row) {
        this.codeGenConfig.form.applicationId = this.queryParams.applicationId;
        this.codeGenConfig.form.tableIds = [];
        const tableIds = row.tableId || this.tableIds;
        if (tableIds == "" && this.queryParams.applicationId == "") {
          this.$modal.msgError("请选择要生成的表或应用！");
          return;
        }else{
          this.codeGenConfig.form.tableIds = tableIds;
        }
        this.codeGenConfig.open = true;
        this.codeGenConfig.genType = row.genType;
        this.codeGenConfig.genPath = row.genCode;
      },
      /** 生成代码操作 */
      handleCodeGenConfig() {
        if (this.codeGenConfig.form.genType === "1") {
          if(this.codeGenConfig.form.tableIds.length>0){
            genCode(this.codeGenConfig.form.tableIds).then(response => {
              this.$modal.msgSuccess("成功生成到自定义路径：" + this.codeGenConfig.genPath);
            });
          } else {
            this.$modal.msgSuccess("生成失败，未选择任何需要生成的实体表！");
          }
        } else {
          if(this.codeGenConfig.form.tableIds.length>0){
            this.$download.zip("/code/table/batchGenCode", "pandamimi", this.codeGenConfig.form);
          } else if(this.queryParams.applicationId){
            this.$download.zip("/code/application/genCode", "pandamimi", this.codeGenConfig.form);
          } else {
            this.$modal.msgSuccess("生成失败，未选择任何需要生成的实体表或应用！");
          }
        }
        this.codeGenConfig.open = false;
      },
      /** 同步数据库操作 */
      handleSyncDb(row) {
        let tableName, tableIds = row.tableId || this.tableIds;
        if (tableIds === "") {
          this.$modal.msgError("请选择要同步的数据");
          return;
        }
        if (row.tableName) {
          if (row.tableComment) {
            tableName = row.tableComment + "[" + row.tableName + "]";
          } else {
            tableName = row.tableName;
          }
        } else {
          tableName = '(' + tableIds + ')等' + tableIds.length + '张表';
        }
        this.$modal.confirm('确认要强制同步 ' + tableName + ' 的表结构吗？').then(function() {
          return syncDb(tableIds);
        }).then(() => {
          this.$modal.msgSuccess("同步成功");
        }).catch(() => {});
      },
      /** 打开导入表弹窗 */
      openImportDatasource() {
        this.$refs.import.open();
      },
      /** 打开导入表弹窗 */
      openImportTable() {
        this.$refs.importTable.open();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.dateRange = [];
        this.resetForm("queryForm");
        this.handleQuery();
      },
      /** 预览按钮 */
      handlePreview(row) {
        previewTable(row.tableId).then(response => {
          this.preview.data = response.data;
          this.preview.open = true;
          this.preview.activeName = "domain.java";
        });
      },
      /** 高亮显示 */
      highlightedCode(code, key) {
        const vmName = key.substring(key.lastIndexOf("/") + 1, key.indexOf(".vm"));
        var language = vmName.substring(vmName.indexOf(".") + 1, vmName.length);
        const result = hljs.highlight(language, code || "", true);
        return result.value || '&nbsp;';
      },
      /** 复制代码成功 */
      clipboardSuccess() {
        this.$modal.msgSuccess("复制成功");
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.tableIds = selection.map(item => item.tableId);
        this.single = selection.length !== 1;
        this.multiple = !selection.length;
      },
      /** 修改按钮操作 */
      handleEditTable0(row) {
        const tableId = row.tableId || this.tableIds[0];
        this.$router.push({
          path: '/tool/gen-edit/index',
          query: {
            tableId: tableId,
            pageNum: this.queryParams.pageNum
          }
        });
      },
      /** 修改按钮操作 */
      handleEditTable(row) {
        const tableId = row.tableId || this.tableIds[0];
        const tableName = row.tableName || this.tableNames[0];
        const params = {
          pageNum: this.queryParams.pageNum,
          tableId: row.tableId
        };
        this.$tab.openPage("修改[" + tableName + "]生成配置", '/tool/gen/table-edit/index/' + tableId, params);
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const tableIds = row.tableId || this.tableIds;
        let promptMsg = '是否确认删除名为"' + row.tableName + '"的数据项？';
        if (tableIds.length > 1) {
          promptMsg = '是否确认删除这 ' + tableIds.length + ' 项数据项？';
        }
        this.$modal.confirm(promptMsg).then(function() {
          return delTable(tableIds);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
      },
      handleOptimize(row){
        const tableIds = row.tableId || this.tableIds;
        let promptMsg = '是否确认优化名为"' + row.tableName + '"的项目？';
        if (tableIds.length > 1) {
          promptMsg = '是否确认优化这 ' + tableIds.length + ' 项项目？';
        }
        this.$modal.confirm(promptMsg).then(function() {
          return optimizeTable(tableIds);
        }).then((res) => {
          this.getList();
          this.$modal.msgSuccess("优化完成："+res.msg);
        }).catch(() => {});
      }
    }
  };
</script>
